package com.key.win.system.ctrl;

import com.key.win.base.auth.AuthenticationUtil;
import com.key.win.base.auth.detail.Authentication;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import com.key.win.base.web.Result;
import com.key.win.common.log.annotation.LogAnnotation;
import com.key.win.common.security.annotation.PreAuthorize;
import com.key.win.system.model.SysDevice;
import com.key.win.system.model.SysOrgan;
import com.key.win.system.service.SysDeviceService;
import com.key.win.system.service.SysOrganService;
import com.key.win.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/organ/*")
@Api("Organ相关的api")
public class SysOrganCtrl {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysOrganService sysOrganService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysDeviceService sysDeviceService;

    @PostMapping("/findSysOrganByPaged")
    @ApiOperation(value = "Organ分页")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public PageResult<SysOrgan> findSysOrganByPaged(@RequestBody PageRequest<SysOrgan> t) {
        return sysOrganService.findSysOrganByPaged(t);
    }
    @PostMapping("/findChildrenNodeByParentId")
    @ApiOperation(value = "获取当前树节点的所有孩子节点&分页")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public  PageResult<SysOrgan> findChildrenNodeByParentId(@RequestBody PageRequest<SysOrgan> t){
        return sysOrganService.findChildrenNodeByParentId(t);
    }

    @PostMapping("/findParentNodeByParentId")
    @ApiOperation(value = "获取当前树节点的所有父节点&分页")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public  PageResult<SysOrgan> findParentNodeByParentId(@RequestBody PageRequest<SysOrgan> t){
        return sysOrganService.findParentNodeByParentId(t);
    }


    @GetMapping("/get/{id}")
    @ApiOperation(value = "获取Organ")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public Result get(@PathVariable String id) {
        return Result.succeed(sysOrganService.getById(id));
    }

    @GetMapping("/getOrganFull/{id}")
    @ApiOperation(value = "获取Organ,包含的当前机构所持有的设备列表信息")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public Result getFull(@PathVariable String id) {
        SysOrgan byId = sysOrganService.getById(id);
        if (byId != null) {
            byId.setSysDevices(sysDeviceService.findDeviceByOrganId(id));
        }
        return Result.succeed(byId);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除")
    @LogAnnotation(module = "system", recordRequestParam = true)
    public Result delete(@PathVariable String id) {
        boolean b = sysOrganService.deleteById(id);
        return Result.result(b);
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "新增/更新")
    @LogAnnotation(module = "system", recordRequestParam = true)
    public Result saveOrUpdate(@RequestBody SysOrgan sysOrgan) {
        if (StringUtils.isBlank(sysOrgan.getCode())) {
            logger.error("机构code为空！");
            throw new IllegalArgumentException("机构code为空！");
        }
        if (StringUtils.isBlank(sysOrgan.getName())) {
            logger.error("机构名称为空！");
            throw new IllegalArgumentException("机构名称为空！");
        }
        if (StringUtils.isBlank(sysOrgan.getParentId())) {
            logger.error("parent Id is null !");
            throw new IllegalArgumentException("父节点为空！");
        }
        boolean b = sysOrganService.saveOrUpdateOrgan(sysOrgan);
        return Result.result(b);
    }

    @GetMapping("/getOrganAll")
    @ApiOperation(value = "所有机构信息")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public Result getOrganAll() {
        return Result.succeed(sysOrganService.list());
    }

    @GetMapping("/getOrganByParenId/{parentId}")
    @ApiOperation(value = "根据父节点获取所有孩子节点")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public Result getOrganByParenId(@PathVariable String parentId) {
        return Result.succeed(sysOrganService.findSysOrganByParentId(parentId));
    }

    @GetMapping("/getOrganTree")
    @ApiOperation(value = "获取机构树")
    @PreAuthorize("@rbacService.hasRole('abc')")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public Result getOrganTree() {
        return Result.succeed(sysOrganService.getOrganTree());
    }

    @GetMapping("/getOrganTree/current/user")
    @ApiOperation(value = "获取当前人所管理的机构树")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public Result getOrganTreeByCurrent() {
        Authentication authentication = AuthenticationUtil.getAuthentication();
        List<SysOrgan> currentUserHoldOrgan = new ArrayList<>();
        Set<String> organIds = null;
        if (org.springframework.util.CollectionUtils.isEmpty(authentication.getSysUserOrgans())) {
            List<SysOrgan> organByUserId = userService.getOrganByUserId(authentication.getId());
            if (!org.springframework.util.CollectionUtils.isEmpty(organByUserId)) {
                organIds = organByUserId.stream().map(organ -> organ.getId()).collect(Collectors.toSet());
            }
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(organIds)) {
            for (String organId : organIds) {
                List<SysOrgan> organTree = sysOrganService.getOrganTree();
                getOrganByTree(currentUserHoldOrgan, organId, organTree);
            }
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(organIds)) {
            loadDeviceByOrganId(currentUserHoldOrgan);
        }
        return Result.succeed(currentUserHoldOrgan);
    }

    private void loadDeviceByOrganId(List<SysOrgan> currentUserHoldOrgan) {
        for (SysOrgan sysOrgan : currentUserHoldOrgan) {
            List<SysDevice> deviceByOrganId = sysDeviceService.findDeviceByOrganId(sysOrgan.getId());
            sysOrgan.setSysDevices(deviceByOrganId);
            if (org.springframework.util.StringUtils.isEmpty(sysOrgan.getSubOrgan())) {
                this.loadDeviceByOrganId(sysOrgan.getSubOrgan());
            }
        }
    }


    private void getOrganByTree(List<SysOrgan> currentUserHoldOrgan, String organId, List<SysOrgan> organTree) {
        for (SysOrgan sysOrgan : organTree) {
            if (organId.equals(sysOrgan.getId())) {
                currentUserHoldOrgan.add(sysOrgan);
                return;
            }
            if (org.springframework.util.StringUtils.isEmpty(sysOrgan.getSubOrgan())) {
                this.getOrganByTree(sysOrgan.getSubOrgan(), organId, organTree);
            }
        }
    }


    @GetMapping("/findLeafNode")
    @ApiOperation(value = "获取所有叶节点")
    @LogAnnotation(module = "system", recordRequestParam = false)
    public Result getLeafNode() {
        return Result.succeed(sysOrganService.findLeafNode());
    }

    @PostMapping("/user/granted")
    @ApiOperation(value = "机构挂载用户")
    @LogAnnotation(module = "system", recordRequestParam = true)
    public Result setUserToOrgan(@RequestBody SysOrgan sysOrgan) {
        if (CollectionUtils.isEmpty(sysOrgan.getUserIds())) {
            logger.error("授权用户为空！");
            throw new IllegalArgumentException("授权用户为空！");
        }
        if (StringUtils.isBlank(sysOrgan.getId())) {
            logger.error("机构信息为空！");
            throw new IllegalArgumentException("机构信息为空！");
        }
        sysOrganService.setUserToOrgan(sysOrgan.getId(), sysOrgan.getUserIds());
        return Result.succeed("机构挂载用户成功！");
    }

    @PostMapping("/user/ap/granted")
    @ApiOperation(value = "机构挂载用户")
    @LogAnnotation(module = "system", recordRequestParam = true)
    public Result setUserToOrganAndAdministrativePermissions(@RequestBody SysOrgan sysOrgan) {
        if (CollectionUtils.isEmpty(sysOrgan.getOrganUsers())) {
            logger.error("授权用户为空！");
            throw new IllegalArgumentException("授权用户为空！");
        }
        if (StringUtils.isBlank(sysOrgan.getId())) {
            logger.error("机构信息为空！");
            throw new IllegalArgumentException("机构信息为空！");
        }
        sysOrganService.setUserToOrgan(sysOrgan.getId(), sysOrgan.getOrganUsers());
        return Result.succeed("机构挂载用户成功！");
    }
}
